package com.shigu.core.config;

import com.alibaba.fastjson.JSONObject;
import com.shigu.exceptions.BaohuoException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * 异常拦截
 *
 * @author wxc
 * @date 2016年6月15日 上午11:21:14
 */
@Component
public class ExceptionResolver extends SimpleMappingExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response, Object arg2, Exception ex) {
        String message = ex.getMessage() == null ? "请求失败，联系管理员" : ex.getMessage();
        //拿到所有参数
        StringBuffer sb = new StringBuffer();
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            sb.append(name);
            sb.append("=");
            sb.append(request.getParameter(name));
            sb.append(",");
        }

        if (!(ex instanceof BaohuoException)) {
            logger.error("系统处理异常[" + request.getRequestURI() + "]，=======" + sb.toString(), ex);
        } else {
            logger.debug(ex.toString() + "[" + request.getRequestURI() + "]，@@@@@@@" + sb.toString(), ex);
        }

        if (request.getServletPath().endsWith(".json")) {//json类型的问题
            JSONObject obj = JSONObject.parseObject("{\"success\":false}");
            obj.put("msg",message);
            String jsonString=obj.toJSONString();
            response.setCharacterEncoding("UTF-8");
            if (request.getParameter("callback") != null) {
                response.setContentType("application/x-javascript");//jsonp异常响应处理
                jsonString = request.getParameter("callback") + "(" + jsonString + ");";
            } else {
                response.setContentType("application/json");//修复post异常信息未被解析为json
            }
            return writeString(response, jsonString);

        } else if (ex instanceof BaohuoException) {//页面已知的错误
            request.setAttribute("errMsg", message);
        } else if (ex instanceof UnauthorizedException) {//权限错误
            return getModelAndView("common/403", ex, request);
        } else {//页面未知的错误
            request.setAttribute("errMsg", "管理系统异常");
        }
        //记录异常日志...
        return getModelAndView("common/500", ex, request);
    }

    private ModelAndView writeString(HttpServletResponse response, String msg) {
        try {
            PrintWriter writer = response.getWriter();
            writer.print(msg);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error("IO流异常", e);
        }
        return null;
    }
}
